<?php namespace Admin\Model;

use Hdphp\Model\ViewModel;

class Login extends ViewModel
{
    //表名
    protected $table = 'user';
    
    //视图
    protected $view = array(
        'role' => array('action' => 'join','on'=>'hd_user.rid=hd_role.rid')
        );

    //验证
    protected $validate = array(
        array('username', 'required', '帐号不能为空', 3),
        array('password', 'required', '密码不能为空', 3),
        array('code', 'required', '验证码不能为空', 3)
        );

    /**
     * 登录
     * @return bool
     */
    public function login()
    {
        if ($this->validate())
        {

            
            //头像设置
            if (empty($user['icon']) || !is_file($user['icon']))
            {
                $user['icon'] = __PUBLIC__ . '/image/user.png';
            }
            else
            {
                $user['icon'] = __ROOT__ . '/' . $user['icon'];
            }
            
            //删除不需要的字段
            unset($user['password']);
            unset($user['code']);

            Session::set('user', $user);

            //登录信息修改
            $this->log();

            return true;
        }
    }

    /**
     * 验证密码
     * @param  int      $uid      用户id
     * @param  string   $password 比对的密码
     * @return bool         
     */
    public function checkPassword($uid,$password)
    {
        if($user = Api('User/get',[$uid]))
        {
            return md5($user['password'].$user['code'])==$password;
        }

    }

    /**
     * 更改登录信息
     */
    public function log()
    {
        $user = $this->find($_SESSION['user']['uid']);
        $data = array(
            'uid'       => $_SESSION['user']['uid'],
            'logintime' => time(),
            'lastip'    => Request::ip()
            );

        return $user->save($data);
    }
}